﻿using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;

namespace ModelRelationship.OneToManyRelationship
{

    /// <summary>
    /// 一对多实体关系配置和树形实体
    /// </summary>
    public class OneToManyRelationshipDbContext : DbContext
    {
        public DbSet<User> Users => Set<User>();

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>(b =>
            {
                b.HasOne(u => u.Creator)
                .WithMany(u => u.CreatedUsers)
                .HasForeignKey(u => u.CreatorId);

                b.HasOne(u => u.LastModifier)
                .WithMany(u => u.LastModifiedUsers)
                .HasForeignKey(u => u.LastModifierId);

            });
        }
    }


    public class User
    {
        [ForeignKey("Creator")]
        public int? CreatorId { get; set; }
        [ForeignKey("CreatorId")]
        [InverseProperty("CreatedUsers")]
        public User Creator { get; set; }
        [ForeignKey("Creator")]
        public List<User> CreatedUsers { get; set; } = new List<User>();
        [ForeignKey("LastModifier")]
        public int? LastModifierId { get; set; }
        [ForeignKey("LastModifierId")]
        [InverseProperty("LastModifiedUsers")]
        public User LastModifier { get; set; }

        [InverseProperty("LastModifer")]
        public List<User> LastModifiedUsers { get; set; } = new List<User>();

    }
}
